package com.cx.controller;

import okhttp3.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.EOFException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @program: pms
 * @author: cx
 * @description: 用于做接口测试
 * @create: 2025-04-22 10:31
 **/
@RestController
@RequestMapping("/test")
public class TestController {

    @PostMapping("/uploadFile")
    public String uploadFileController(String token, String taskId, MultipartFile file) throws IOException {
        try {
            // 记录上传文件的日志
            System.out.println("Uploading file: " + file.getOriginalFilename() + " for taskId: " + taskId);
            String result = uploadFile(token, taskId, file);
            return result;
        } catch (IOException e) {
            // 记录错误日志
            System.err.println("Error uploading file: " + e.getMessage());
            throw e; // 重新抛出异常，以便上层处理
        }
    }

    public static String uploadFile(String token, String taskId, MultipartFile file) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)  // 连接超时时间
                .readTimeout(30, TimeUnit.SECONDS)     // 读取超时时间
                .writeTimeout(30, TimeUnit.SECONDS)    // 写入超时时间
                .build();

        try {
            RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("file", file.getOriginalFilename(),
                            RequestBody.create(MediaType.parse("application/octet-stream"),
                                    file.getBytes()))
                    .addFormDataPart("taskId", taskId)
                    .addFormDataPart("language", "2")
                    .addFormDataPart("parameter", "{\"isAllowOCR\": 1, \"language\": \"chi_sim\"}")
                    .build();
            // 确保URL以http://或https://开头
            String url = "https://api-server.compdf.com/server/v1/file/upload";
            if (!url.startsWith("http://") && !url.startsWith("https://")) {
                url = "https://" + url;
            }
            Request request = new Request.Builder()
                    .url(url)
                    .method("POST", body)
                    .addHeader("Authorization", "Bearer " + token)
                    .build();
            Response response = client.newCall(request).execute();

            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response.code() + ": " + response.message());
            }
            return response.body().string();

        } catch (IOException e) {
            throw new IOException("上传文件失败: " + e.getMessage(), e);
        }
    }


}

